from django.db import models

# Create your models here.
from django.db import models
from utils.models import BaseModel
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer,SignatureExpired,BadSignature, BadData
from django.conf import settings


class OAuthQQUser(BaseModel):
    """
    QQ登录用户数据
    """
    # 1对1,1对多   级联操作
    # 主表数据删除，子表数据该怎么做

    # 主表删  子表也删
    # 主表删  子表不让删
    # 主表删  子表设置为null

    # 外键 关联的时候是想关联  其他子应用的模型类，  语法为：子应用.模型类
    user = models.ForeignKey('users.User', on_delete=models.CASCADE, verbose_name='用户')
    openid = models.CharField(max_length=64, verbose_name='openid', db_index=True)

    class Meta:
        db_table = 'tb_oauth_qq'
        verbose_name = 'QQ登录用户数据'
        verbose_name_plural = verbose_name

        # 对象方法  def generic_token_by_openid(self,openid):

        # 类方法        @classmethod
        #               def generic_token_by_openid(cls,openid):

        # 静态方法
        #     @staticmethod
        #     def generic_token_by_openid(openid):
    @staticmethod
    def generic_token_by_openid(openid):
        # 1.创建序列化器
        serializer = Serializer(settings.SECRET_KEY, 3600)
        # 2.加密处理
        token = serializer.dumps({'openid': openid})
        return token.decode()
    @staticmethod
    def openid_by_token(access_token):
        # 1.创建序列化器
        serializer = Serializer(settings.SECRET_KEY, 3600)
        #2.解密
        try:
            result = serializer.loads(access_token)
        except BadData:
            return None
        else:
            return result.get('openid')